"""
API配置管理模块
管理与学生管理系统和Compreface的API配置
"""

import yaml
import os
from typing import Dict, Any, List


class APIConfigManager:
    def __init__(self, config_file: str = "config/api_config.yaml"):
        """
        初始化API配置管理器
        :param config_file: API配置文件路径
        """
        self.config_file = config_file
        self.config = {}
        self.load_config()
    
    def load_config(self) -> Dict[str, Any]:
        """
        从配置文件加载API配置
        :return: API配置字典
        """
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    self.config = yaml.safe_load(f)
            else:
                # 创建默认配置
                self.config = self._create_default_config()
                self.save_config()
            return self.config
        except Exception as e:
            print(f"加载配置文件失败: {e}")
            # 返回默认配置
            self.config = self._create_default_config()
            return self.config
    
    def _create_default_config(self) -> Dict[str, Any]:
        """
        创建默认配置
        :return: 默认配置字典
        """
        return {
            "student_management_system": {
                "base_url": "http://localhost:8080",
                "api_prefix": "/api",
                "auth": {
                    "type": "token",
                    "token": "your-api-token-here"
                },
                "endpoints": {
                    "get_student": "/student/{id}",
                    "get_all_students": "/student",
                    "create_student": "/student",
                    "update_student": "/student/{id}",
                    "delete_student": "/student/{id}"
                },
                "timeout": 30,
                "retries": 3
            },
            "compreface": {
                "base_url": "http://localhost:8081",
                "api_key": "your-compreface-api-key",
                "endpoints": {
                    "recognize": "/api/recognition/recognize",
                    "add_face": "/api/faces",
                    "delete_face": "/api/faces/{id}"
                }
            }
        }
    
    def save_config(self) -> bool:
        """
        保存配置到文件
        :return: 是否保存成功
        """
        try:
            # 确保配置目录存在
            config_dir = os.path.dirname(self.config_file)
            if config_dir and not os.path.exists(config_dir):
                os.makedirs(config_dir)
                
            with open(self.config_file, 'w', encoding='utf-8') as f:
                yaml.dump(self.config, f, allow_unicode=True, default_flow_style=False)
            return True
        except Exception as e:
            print(f"保存配置文件失败: {e}")
            return False
    
    def update_config(self, new_config: Dict[str, Any]) -> bool:
        """
        更新API配置
        :param new_config: 新的API配置
        :return: 更新是否成功
        """
        try:
            self.config.update(new_config)
            return self.save_config()
        except Exception as e:
            print(f"更新配置失败: {e}")
            return False
    
    def validate_connection(self) -> bool:
        """
        验证API连接是否有效
        :return: 连接是否有效
        """
        # 这里应该实现实际的连接验证逻辑
        # 由于这是一个示例，我们简单返回True
        return True
    
    def get_student_info(self, student_id: str) -> Dict[str, Any]:
        """
        获取学生信息
        :param student_id: 学生ID
        :return: 学生信息字典
        """
        # 这里应该实现实际的API调用逻辑
        # 由于这是一个示例，我们返回模拟数据
        return {
            "id": student_id,
            "name": "张三",
            "class": "计算机科学与技术1班"
        }
    
    def get_all_students(self) -> list[Dict[str, Any]]:
        """
        获取所有学生信息
        :return: 学生信息列表
        """
        # 这里应该实现实际的API调用逻辑
        # 由于这是一个示例，我们返回模拟数据
        return [
            {"id": "001", "name": "张三", "class": "计算机科学与技术1班"},
            {"id": "002", "name": "李四", "class": "计算机科学与技术1班"},
            {"id": "003", "name": "王五", "class": "计算机科学与技术2班"}
        ]